package org.dreamwork.jasmine2.jxd;

import org.dreamwork.misc.BASE64Zipper;

import java.net.URL;
import java.net.URLDecoder;
import java.net.URISyntaxException;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2008-12-24
 * Time: 14:30:37
 */
public class InternalResourceManager {
    public static final String ENCODING = "utf-8";

    public static String getResource (Class clazz, String resource) throws Exception {
        File file = getPhysicalFile (clazz);
        if (file == null) return null;
        String d;
        if (!file.getAbsolutePath ().endsWith (".jar")) {
            String path = file.getAbsolutePath ().replace ('\\', '/');
            String cls =  clazz.getName ().replace ('.', '/') + ".class";
            d = path.substring (0, path.lastIndexOf (cls));
        } else {
            d = file.getAbsolutePath ();
        }
        d += "|" + resource;
        BASE64Zipper zipper = new BASE64Zipper ();
        zipper.setEncoding (ENCODING);
        d = zipper.DESEncodeString(d);
        return "d=" + d + "&amp;t=" + file.lastModified ();
    }

    public static File getPhysicalFile (Class clazz) throws IOException, URISyntaxException {
        ClassLoader loader = clazz.getClassLoader ();
        String classFileName = clazz.getName ().replace ('.', '/') + ".class";
        URL url = loader.getResource (classFileName);
        if (url != null) {
            String path = url.getPath ();
            if (path.startsWith ("file:")) path = path.substring ("file:".length ());
            int pos = path.indexOf (".jar!");
            if (pos > 0) { // jar file
                path = path.substring (0, pos + 4);
                path = URLDecoder.decode (path, System.getProperty ("file.encoding", ENCODING));
                File file = new File (path);
                return file.exists () ? file : null;
            } else { // path
                return new File (path);
            }
        }
        return null;
    }
}